namespace EyeSoft.Wpf.Facilities
{
	using System;
	using System.Collections.Generic;
	using System.Linq.Expressions;

	using EyeSoft.Reflection;

	internal class PropertiesChanges
	{
		private readonly IDictionary<string, List<PropertyChangeMetadata>> changeActions =
			new Dictionary<string, List<PropertyChangeMetadata>>();

		public void AddChangeActionOn<TProperty>(Expression<Func<TProperty>> property, Action<TProperty> action, int times)
		{
			var propertyName = property.PropertyName();

			if (!changeActions.ContainsKey(propertyName))
			{
				changeActions[propertyName] = new List<PropertyChangeMetadata>();
			}

			changeActions[propertyName].Add(new PropertyChangeMetadata(times, action));
		}

		public void ActionOnProperty(string propertyName, object propertyValue)
		{
			if (!changeActions.ContainsKey(propertyName))
			{
				return;
			}

			var propertyChangeActions = changeActions[propertyName];

			foreach (var propertyChangeAction in propertyChangeActions)
			{
				if (propertyChangeAction.HasToExecute)
				{
					propertyChangeAction.Execute(propertyValue);
				}

				propertyChangeAction.Changed();
			}
		}
	}
}